package logic

import (
	"context"
	"fmt"
	"math"
	"my-zero-tiktok/common/constant"
	"my-zero-tiktok/common/paginate"
	"strconv"

	"my-zero-tiktok/apps/user/pb/pb"
	"my-zero-tiktok/apps/user/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FollowerUserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFollowerUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FollowerUserListLogic {
	return &FollowerUserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// FollowerUserList 我的粉丝列表
func (l *FollowerUserListLogic) FollowerUserList(in *pb.UserListRequest) (*pb.UserListResponse, error) {
	var userIDs []int64
	fanKey := fmt.Sprintf("%s:%d", constant.FanKey, in.Id)
	pairs, err := l.svcCtx.Redis.ZrevrangebyscoreWithScoresAndLimitCtx(
		l.ctx, fanKey, 0, math.MaxInt, int(in.Page), int(in.PerPage),
	)

	if err == nil && len(pairs) > 0 {
		for _, pair := range pairs {
			id, _ := strconv.ParseInt(pair.Key, 10, 64)
			userIDs = append(userIDs, id)
		}
	} else {
		offset := paginate.GetOffset(in.Page, in.PerPage)
		userIDs, _ = l.svcCtx.RelationModel.FanListByPage(l.ctx, in.Id, offset, in.PerPage)
	}

	if len(userIDs) == 0 {
		return &pb.UserListResponse{}, nil
	}

	users, _ := l.svcCtx.UserModel.UserList(l.ctx, userIDs)
	userList := make([]*pb.User, len(users))
	for i, user := range users {
		userList[i] = &pb.User{Id: user.Id, Name: user.Name}
	}
	return &pb.UserListResponse{List: userList}, nil
}
